package com.fang.system.io.mocknetty;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description TODO
 * @date 2022/7/15 2:46 下午
 **/
public class NettyServerBootStrap {

    private EventLoopGroup boss;
    private EventLoopGroup worker;
    private ServerAcceptor serverAcceptor;

    public NettyServerBootStrap group(EventLoopGroup boss, EventLoopGroup worker) {
        this.boss = boss;
        this.worker = worker;
        return this;
    }

    public void bind(int port) throws IOException {
        ServerSocketChannel server = ServerSocketChannel.open();
        server.configureBlocking(false);
        server.bind(new InetSocketAddress(port));
        start(server);
    }

    private void start(ServerSocketChannel server) {
        serverAcceptor = new ServerAcceptor(worker, server);
        EventLoop eventLoop = boss.chooser();
        // 启动server、bind端口的操作变成task，推送到eventLoop中执行
        eventLoop.execute(() -> {
            try {
                eventLoop.eventLoopName = Thread.currentThread().getName() + "___" + eventLoop.eventLoopName;
                System.out.println("bind server to " + eventLoop.eventLoopName);
                server.register(eventLoop.selector, SelectionKey.OP_ACCEPT, serverAcceptor);
            } catch (ClosedChannelException e) {
                e.printStackTrace();
            }
        });
    }
}
